from flask import Blueprint, request, Response, jsonify
import json
from models import User
from settings import db

from flask import render_template, redirect
from models import House

user_page = Blueprint('user_page',__name__)
@user_page.route('/register', method=["POST"])
def register():
    # 获取用户的注册信息，包括用户名、密码、邮箱
    name = request.form['username']
    password = request.form['password']
    email = password.form['email']
    # 查询数据库中是否存在该用户名
    result = User.query.filter(User.name == name).all()
    # 判断用户名是否已经注册,如果没有注册在返回结果中设置Cookie
    if len(result) == 0:    # 若用户名不存在,说明未注册,则将注册信息保存到数据库中,并在Cookie中设置过期时间
        user = User(name=name, password=password, email=email)
        db.session.add(user)
        db.session.commit()
        json_str = json.dumps({'valid': '1', 'msg': user.name})
        res = Response(json_str)
        res.set_cookie('name', user.name, 3600 * 2)     # 设置Cookie过期时间
        return res
    else:                  # 若用户名存在，说明已注册，则返回用户已注册的信息
        return jsonify({'valid': '0', 'msg': '用户已注册'})

user_page.route('/user/<name>')
def user(name):
    # 查询数据库中名为name的User类对象
    user = User.query.filter(User.name == name).first()
    # 判断用户名是否存在
    if user:  # 该用户名存在
        collect_id_str = user.collect_id    # 获取当前用户收藏的房源ID
        if collect_id_str:                  # 若collect_id_str不为空
            collect_id_str = collect_id_str.split(',')
            collect_house_list = []
            # 根据房源ID获取对应的房源对象
            for hid in collect_id_str:
                house = House.query.get(int(hid))
                # 将房源对象添加到列表中
                collect_house_list.append(house)
        else:                               # 若collect_id_str为空
            collect_house_list = []
        seen_id_str = user.seen_id          # 获取当前用户的浏览记录
        if seen_id_str:
            seen_id_str = seen_id_str.split(',')
            seen_house_list = []
        else:
            seen_house_list = []
        return render_template('user_page.html', user=user, collect_house_list=collect_house_list, seen_house_list=seen_house_list)
    else:
        #重定向到首页
        return redirect('/')